import { Message } from '@arco-design/web-vue';
import { IconDashboard, IconList, IconLock, IconSafe, IconSettings, IconUser } from '@arco-design/web-vue/es/icon';
import NProgress from 'nprogress';
import type { Component } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';

import { useUserStore } from '@/stores';
import { AdminType, type RouteMetaWithPermission } from '@/types/permission';

import 'nprogress/nprogress.css';

/**
 * 菜单项接口定义
 * 统一的菜单项类型，支持多层级子菜单
 */
export interface MenuItem {
  name: string; // 菜单项唯一标识
  title: string; // 显示标题
  icon?: Component; // 图标名称
  path?: string; // 路由路径
  component?: () => Promise<Component>; // 组件懒加载函数
  children?: MenuItem[]; // 子菜单项
  adminTypes?: AdminType[]; // 允许的管理员类型
  hidden?: boolean; // 是否隐藏
  requiresTenant?: boolean; // 是否需要租户上下文
}

export const menus: MenuItem[] = [
  {
    name: 'Dashboard',
    title: '仪表盘',
    icon: IconDashboard,
    path: '/dashboard',
    component: () => import('@/views/dashboard/index.vue'),
    adminTypes: [AdminType.SUPER_ADMIN, AdminType.SCHOOL_ADMIN]
  },
  {
    name: 'UserManagement',
    title: '用户管理',
    icon: IconUser,
    adminTypes: [AdminType.SUPER_ADMIN, AdminType.SCHOOL_ADMIN],
    children: [
      {
        name: 'UserList',
        title: '用户列表',
        icon: IconList,
        path: '/users/list',
        component: () => import('@/views/sample/index.vue'),
        adminTypes: [AdminType.SUPER_ADMIN, AdminType.SCHOOL_ADMIN]
      },
      {
        name: 'UserRoles',
        title: '角色管理',
        icon: IconSafe,
        path: '/users/roles',
        component: () => import('@/views/sample/index.vue'),
        adminTypes: [AdminType.SUPER_ADMIN]
      },
      {
        name: 'UserPermissions',
        title: '权限管理',
        icon: IconLock,
        adminTypes: [AdminType.SUPER_ADMIN],
        children: [
          {
            name: 'PermissionList',
            title: '权限列表',
            path: '/users/permissions/list',
            component: () => import('@/views/sample/index.vue'),
            adminTypes: [AdminType.SUPER_ADMIN]
          },
          {
            name: 'PermissionGroups',
            title: '权限分组',
            path: '/users/permissions/groups',
            component: () => import('@/views/sample/index.vue'),
            adminTypes: [AdminType.SUPER_ADMIN]
          }
        ]
      }
    ]
  },
  {
    name: 'SystemSettings',
    title: '系统设置',
    icon: IconSettings,
    path: '/settings',
    component: () => import('@/views/settings/index.vue'),
    adminTypes: [AdminType.SUPER_ADMIN] // 仅超级管理员可访问
  }
];
// 扩展路由记录以包含权限元信息
// 注意：ExtendedRouteRecordRaw 用于路由配置，MenuItem 用于菜单显示
// 两者结构相似但用途不同，路由配置包含组件加载等路由特有属性
interface ExtendedRouteRecordRaw {
  path: string;
  name?: string;
  component?: () => Promise<Component>;
  redirect?: string;
  meta?: RouteMetaWithPermission;
  children?: ExtendedRouteRecordRaw[];
}

// 配置NProgress
NProgress.configure({
  showSpinner: false,
  minimum: 0.2,
  speed: 500
});

// 将MenuItem转换为路由配置的函数
function convertMenuToRoute(menuItem: MenuItem): ExtendedRouteRecordRaw | null {
  // 如果没有path且没有children，跳过
  if (!menuItem.path && !menuItem.children) {
    return null;
  }

  const route: ExtendedRouteRecordRaw = {
    path: menuItem.path || '',
    name: menuItem.name,
    component: menuItem.component,
    meta: {
      title: menuItem.title,
      adminTypes: menuItem.adminTypes,
      hidden: menuItem.hidden,
      requiresTenant: menuItem.requiresTenant
    }
  };

  // 处理子菜单
  if (menuItem.children && menuItem.children.length > 0) {
    const childRoutes = menuItem.children
      .map(convertMenuToRoute)
      .filter((route): route is ExtendedRouteRecordRaw => route !== null);

    if (childRoutes.length > 0) {
      route.children = childRoutes;
    }
  }

  return route;
}

// 从allMenuTree生成路由配置
function generateRoutesFromMenuTree(): ExtendedRouteRecordRaw[] {
  return menus
    .map(convertMenuToRoute)
    .filter((route): route is ExtendedRouteRecordRaw => route !== null)
    .map((route) => {
      // 处理路径，移除开头的斜杠以适配子路由
      if (route.path && route.path.startsWith('/')) {
        route.path = route.path.substring(1);
      }
      return route;
    });
}

// 路由配置 - 基于allMenuTree动态生成
const routes: ExtendedRouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: '管理员登录',
      requiresAuth: false,
      hidden: true
    }
  },
  {
    path: '/',
    component: () => import('@/layout/index.vue'),
    children: generateRoutesFromMenuTree() // 从allMenuTree生成子路由
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('@/views/exception/403.vue'),
    meta: {
      title: '访问被拒绝',
      hidden: true
    }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/exception/404.vue'),
    meta: {
      title: '页面不存在',
      hidden: true
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
];

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes as RouteRecordRaw[], // 类型转换
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  }
});

// 全局前置守卫 - 增强权限检查
router.beforeEach(async (to, from, next) => {
  // 开始进度条
  NProgress.start();

  const userStore = useUserStore();

  // 等待用户状态初始化完成
  if (!userStore.isInitialized) {
    // 如果还没有初始化，等待初始化完成
    let retryCount = 0;
    const maxRetries = 50; // 最多等待5秒
    while (!userStore.isInitialized && retryCount < maxRetries) {
      await new Promise((resolve) => setTimeout(resolve, 100));
      retryCount++;
    }
  }

  // 设置页面标题
  const title = to.meta?.title as string;
  if (title) {
    document.title = `${title} - 福农跑腿管理后台`;
  }

  // 如果是登录页面，且已经登录，则跳转到仪表板或指定页面
  if (to.name === 'Login' && userStore.isLoggedIn) {
    const redirectPath = to.query.redirect as string;
    if (redirectPath) {
      next({ path: redirectPath });
    } else {
      next('/dashboard');
    }
    return;
  }

  // 如果页面不需要认证，直接放行
  if (!to.meta?.requiresAuth) {
    next();
    return;
  }

  // 基础认证检查
  if (!userStore.isLoggedIn) {
    Message.warning('请先登录');
    next({
      name: 'Login',
      query: { redirect: to.fullPath }
    });
    return;
  }

  try {
    // 如果用户信息不存在，尝试获取
    if (!userStore.userInfo) {
      await userStore.fetchUserInfo();
    }

    // 管理员类型检查
    if (to.meta?.adminTypes && Array.isArray(to.meta.adminTypes)) {
      const currentAdminType = userStore.adminType;
      if (!currentAdminType || !to.meta.adminTypes.includes(currentAdminType)) {
        Message.error('权限不足，无法访问该页面');
        next({ name: 'Forbidden' });
        return;
      }
    }

    // 租户上下文检查（仅对学校管理员）
    if (to.meta?.requiresTenant && userStore.isSchoolAdmin) {
      if (!userStore.currentTenant) {
        Message.warning('请先选择要管理的学校');
        // 可以跳转到租户选择页面或仪表板
        next({ name: 'Dashboard' });
        return;
      }
    }

    next();
  } catch (error) {
    console.error('权限检查失败:', error);
    Message.error('登录状态已过期，请重新登录');
    userStore.clearUserData();
    next({
      name: 'Login',
      query: { redirect: to.fullPath }
    });
  }
});

// 全局后置守卫
router.afterEach((to, from) => {
  // 结束进度条
  NProgress.done();

  // 记录路由跳转日志（仅在开发环境）
  if (import.meta.env.DEV) {
    console.log(`路由跳转: ${from.path || '/'} -> ${to.path}`);
  }
});

// 路由错误处理
router.onError((error) => {
  console.error('路由错误:', error);
  NProgress.done();
  Message.error('页面加载失败，请刷新重试');
});

// 导出路由实例和路由相关工具
export default router;
export type { ExtendedRouteRecordRaw };
